/**
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */

package org.geoscheduler.rest;

import org.geoscheduler.commons.msgs.types.AccountMsgs;
import org.geoscheduler.commons.msgs.types.GeneralMsgs;
import org.geoscheduler.commons.tools.StringTools;
import org.geoscheduler.exceptions.GSAuthorizationException;
import org.geoscheduler.exceptions.JSONWrappedException;
import org.geoscheduler.model.Account;
import org.geoscheduler.model.Token;
import org.json.JSONException;

public abstract class AbstractAccountDependantResource extends AbstractResource {
	
	protected AbstractAccountDependantResource(){
		super();
	}
	
	protected Account authorize(String auth, String login, Object data) throws JSONException, GSAuthorizationException {
		Token t = getContext().getAuthorizationProvider().authorize(auth, data);
		Account a = loadAccount(login);
		
		if (t.getIdAccount() != a.getId()) {
			throw new GSAuthorizationException("Access denied.");
		}
		
		return a;
	}

	protected Account loadAccount(String login) throws JSONWrappedException {
		if (StringTools.isEmpty(login)) {
			throw new JSONWrappedException(GeneralMsgs.MISSING_CALL_PARAMETER, "login");
		}
		Account account = getContext().getAccountDAO().loadByLogin(login);
		if (account == null) {
			throw new JSONWrappedException(AccountMsgs.INVALID_ACCOUNT, login);
		}
		return account;

	}
}
